package org.wit.ecommerce.dao;

import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.xwork.StringUtils;
import org.hibernate.Query;
import org.wit.ecommerce.domain.Transaction;
/**
 * @spring.bean id="transactionDao"
 * @spring.property name="sessionFactory" ref="sessionFactoryObj"
 * @author Justin
 *
 */
public class TransactionDao extends SimpleHibernateDao<Transaction, Long> {

	/**
	 * 
	 * @param start
	 * @param limit  Max items per page
	 * @param keywords
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Transaction> findByPage(int start, int limit, Map<String, ?> keywords) {
		String select = "from org.wit.ecommerce.domain.Transaction where 1=1";
		String hql = addKeywords(new StringBuffer(select), keywords);
		Query q = createQuery(hql);
		q.setFirstResult(start);
		q.setMaxResults(limit);
		return q.list();
	}
	
	/**
	 * return total rows
	 * @author Justin
	 * @param keywords
	 * @return
	 */
	public int getTotalCount(Map<String, ?> keywords){
		String select = "select count(*) from org.wit.ecommerce.domain.Transaction where 1=1";
		String hql = addKeywords(new StringBuffer(select), keywords);
		return ((Number) createQuery(hql).uniqueResult()).intValue();
	}

	/**
	 * batch delete by ids
	 * @param ids
	 */
	public void batchDelete(Long[] ids) {
		String idsStr = StringUtils.join(ids,",");
		String hql1 = "delete from org.wit.ecommerce.domain.TransactionLog where transactionid in (" + idsStr + ")";
		Query q1 = getSession().createQuery(hql1);
		q1.executeUpdate();
		
		String hql2 = "delete from org.wit.ecommerce.domain.Transaction where id in (" + idsStr + ")";
		Query q2 = getSession().createQuery(hql2);
		q2.executeUpdate();
	}
	
	private String addKeywords(StringBuffer hql, Map<String, ?> keywords){
		String pin = (String)keywords.get("pin");
		String receiverState = (String)keywords.get("receiverState");
		Integer status = (Integer)keywords.get("status");
		Timestamp startDate = (Timestamp)keywords.get("startDate");
		Timestamp endDate = (Timestamp)keywords.get("endDate");
		String phone = (String)keywords.get("phone");
		
		if(StringUtils.isNotBlank(pin)){
			hql.append(" and pin = '").append(pin).append("'");
		}
		if(StringUtils.isNotBlank(receiverState)){
			hql.append(" and receiverState = '").append(receiverState).append("'");
		}
		if(status != null && status != -1){
			System.out.println(status);
			hql.append(" and status = ").append(receiverState);
		}
		if(startDate != null){
			hql.append(" and createDate >= '").append(startDate).append("'");
		}
		if(endDate != null){
			hql.append(" and createDate <= '").append(endDate).append("'");
		}
		if(StringUtils.isNotBlank(phone)){
			hql.append(" and (senderMobile = '").append(phone).append("' or receiverMobile='").append(phone).append("')");
		}
		return hql.toString();
	}
}
